<template>
  <div class="app-container">
    <div class="box ph-30">
      <div class="panel">
        <div class="panel-header">
          <h3 class="panel-title">选择运动员</h3>
        </div>
        <div class="panel-body">
          <div class="text-left mb20">
            <el-button type="primary" @click="chooseSportman" size="large">选择参赛运动员</el-button>
            <el-button type="" @click="importSportman" size="large">批量导入人员</el-button>
            <el-button type="" @click="addCoach" size="large">新增运动员</el-button>
            <el-button v-if="choosedList.length > 0" style="float:right" type="warning" size="large"  @click="delchoosedchoosed" >清空运动员</el-button>
          </div>

          <el-tabs
            v-if="signType=='2'"
            v-model="activeTeam"
            type="card"
            class="demo-tabs"
            @tab-click="teamClick"
          >
            <el-tab-pane v-for="t in teamList" :key="t.id" :label="t.name" :name="t.id" />
          </el-tabs>

          <!-- 已选运动员列表-->
          <div class="hasChoose" v-if="choosedList.length > 0">
            <!-- <el-checkbox-group v-model="choosedchoosed" style="display: flex;flex-wrap: wrap;">
              <div v-for="p in choosedList" class="choseItem">
                <a class="poClose" @click.stop="delthischoosed(p)">
                  <el-icon :size="20" color="#999"><CircleClose /></el-icon>
                </a>
                <el-checkbox border :label="p.id" @click="signForThisMan(p)">
                  {{ p.realName }}
                  <span v-if="p.sex=='1'">(男)</span>
                  <span v-if="p.sex=='0'">(女)</span>
                </el-checkbox>
               
              </div>
            </el-checkbox-group> -->
            <div style="display: flex;flex-wrap: wrap;">
              <div v-for="(p,key) in choosedList" @click="signForThisMan(p)" :key="key" :class="p.id==activeId?'choseItem chooseItemActive':'choseItem'">
                 <p  >
                  {{ p.realName }}
                  <span v-if="p.sex=='1'">(男) </span>
                  <span v-if="p.sex=='0'">(女) </span>
                </p>
                <p v-if="p.id!=activeId"  @click.stop="delthischoosed(p)" style="padding-top:6px;">
                  <el-icon :size="17" ><Delete /></el-icon>
               </p>
              </div>
            </div>
          </div>
         
          <div v-else style="text-align:center;padding:20px">
            <el-button type="danger" plain :icon="Plus" @click="chooseSportman" size="large">请先选择参赛运动员，选中运动员获取报名项目</el-button>
          </div>

        </div>
      </div>
      <div class="panel chooseBottom" v-show="activeId">
      <div>
        <h4 class="formTitle">报项列表</h4>
        <div>
          <dialogSportsmanList ref="dialogSportsmanListRef" @submitForm="getSignInfoList" />
        </div> 
      </div>
      </div>

      <div class="panel chooseBottom">
      <div>
        <h4 class="formTitle">其他人员</h4>
      </div>
        <ul class="mb20 namesUl">
            <li v-show="names.coachList?.length>0"><label>教练 - </label><span v-for="c in names.coachList">{{ c.realName }}</span> </li>
            <li v-show="names.leaderList?.length>0"><label>领队 - </label><span v-for="c in names.leaderList">{{ c.realName }}</span></li>
            <li v-show="names.teamDoctorList?.length>0"><label>队医 - </label><span v-for="c in names.teamDoctorList">{{ c.realName }}</span></li>
            <li v-show="names.translatorList?.length>0"><label>翻译 - </label><span v-for="c in names.translatorList">{{ c.realName }}</span></li>
            <li v-show="names.officialList?.length>0"><label>官员 - </label><span v-for="c in names.officialList">{{ c.realName }}</span></li>
            <li v-show="names.otherList?.length>0"><label>其他 - </label><span v-for="c in names.otherList">{{ c.realName }}</span></li>
          </ul>

          <el-table :data="signInfoTable" style="width: 100%"  border>
            <el-table-column label="序号" type="index" align="center"  width="70px"></el-table-column>
            <el-table-column  label="照片" width="90px" align="center">
              <template #default="scope">
                <div >
                                   <el-image v-if="scope.row.personInfo.picUrl" style="width: 50px; height: 50px" fit="contain" :src="scope.row.personInfo.picUrl" />
                  
                
                </div>
              </template>
            </el-table-column>
            <el-table-column  label="运动员" width="120px" align="center">
              <template #default="scope">
                <div>
                  <!--                  <el-image v-if="scope.row.personInfo.picUrl" style="width: 50px; height: 50px" fit="contain" :src="scope.row.personInfo.picUrl" />-->
                  <p>{{ scope.row.personInfo.realName }}
                  <!-- ({{ scope.row.personInfo.sexStr }}) -->
                  </p>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="性别" width="90px" align="center">
              <template #default="scope">
                <div >
                  <!--                  <el-image v-if="scope.row.personInfo.picUrl" style="width: 50px; height: 50px" fit="contain" :src="scope.row.personInfo.picUrl" />-->
                  <p>{{ scope.row.personInfo.sexStr }}</p>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="报项" align="center">
              <template #default="props">
                <ol>
                  <li v-for="s in props.row.signInfo">
                    {{ s.cptProjectName }}
                    {{ s.cptGroupName }}{{ s.cptLevelName }}
                    <span v-show="s.cptSonLevelName">[{{ s.cptSonLevelName }}]</span>
                    {{ s.zu }}
                    
                        <el-button type="text" @click="editThis(s)">编辑</el-button>
<!--                    <el-button type="text" @click="editMates(s)">更换队友</el-button>-->
                    <el-button type="text" @click="removeThis(s.id)">删除</el-button>

                  </li>
                </ol>
              </template>

            </el-table-column>

            <!--            补充信息-->
            <!--            <el-table-column v-for="(e,index) in extraTableHead" :key="index" :label="e">-->
            <!--              <template #default="scope">-->
            <!--                <el-link v-if="scope.row.signInfo[0].extraPersonInfoMapList[index]?.type=='2'" :herf="scope.row.signInfo[0].extraPersonInfoMapList[index].value.url">-->
            <!--                  {{ scope.row.signInfo[0].extraPersonInfoMapList[index].value.name }}-->
            <!--                </el-link>-->
            <!--                <img v-else-if="scope.row.signInfo[0].extraPersonInfoMapList[index]?.type=='3'" style="width: 50px;" :src="scope.row.signInfo[0].extraPersonInfoMapList[index].value.url||scope.row.signInfo[0].extraPersonInfoMapList[index].value">-->
            <!--                <span v-else>{{ scope.row.signInfo[0].extraPersonInfoMapList[index]?.value }}</span>-->
            <!--              </template>-->
            <!--            </el-table-column>-->
            <el-table-column label="操作" fixed="right" width="150" align="center">
              <template #default="scope">
                <el-button v-if="extraform&&extraform.length>0" type="text" @click="goPersonInfo(scope.row)">
                  <span v-if="scope.row.extraPersonInfo">修改</span>
                  <span v-else class="red">完善补充信息</span>
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        <div class="panel-footer text-center">
          <el-button type="success" plain round @click="goPrev()">上一步</el-button>
          <el-button type="success" round @click="submitForm()">下一步</el-button>
        </div>
      </div>
    </div>
  
    <dialogAddCoach ref="dialogAddCoachRef" />
  
    <dialogAllSportsmanList ref="dialogAllSportsmanListRef" @transfer="getChoosed" @submitForm="getSignInfoList" />

    <dialogMates ref="dialogMatesRef" @submitForm="getSignInfoList" />

    <dialogImport ref="dialogImportProps" @submitForm="getMySignInfo" />

    <el-dialog v-model="showResult" :close-on-click-modal="false" :show-close="false">
      <el-result icon="success" title="报名成功">
        <template #extra>
          <el-button type="primary" @click="downloadVoucher">下载凭证</el-button>
          <el-button type="primary" @click="goMySign">查看报项</el-button>
        </template>
      </el-result>

    </el-dialog>

    <dialogChangeCoach ref="popChangeCoach" @submitForm="getMySignInfo" />

    <dialogExtraForm ref="popExtraForm" @submitForm="getSignInfoList" />
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import * as match from '@/api/match/pc'
import { getCurrentInstance, onMounted } from '@vue/runtime-core'
import dialogAddCoach from './components/addCoach'
import dialogSportsmanList from './components/sportsmanList'
import dialogAllSportsmanList from './components/allSportsmanList'
import dialogImport from './components/import'
import dialogChangeCoach from './components/changeCoach'
import dialogExtraForm from './components/extraForm'
import dialogMates from './components/dialogMates'
const { proxy } = getCurrentInstance()
const router = useRouter()	
const route = useRoute()
import _ from 'lodash'
import { ElMessage, ElMessageBox } from 'element-plus'
import {Plus } from '@element-plus/icons-vue'
const data = reactive({
  coachForm: {},
  tableData: [], signInfoTable: [], choosedList: [],
  extraPersonInfoMapList: [],
  teamList: [],
  extraform: [],
  groupId: '0',
  signType: '',
  coachOrLeaderFlag: null,
  noPhotoCanSign: null,
  showResult: false,
  showExtraForm: false,
  extraTableHead: [],
  activeTeam: '',
  names: {},
  choosedchoosed: [],
})
const { activeTeam, names, tableData, signInfoTable, choosedList, showExtraForm, extraPersonInfoMapList, teamList,
  extraform, groupId, signType, coachOrLeaderFlag, showResult, noPhotoCanSign, extraTableHead,
  coachForm, choosedchoosed } = toRefs(data)
let activeId= ref(null)
let matchId = ''
let signInfoType = null
onMounted(() => {
  groupId.value = route.query.groupId
  signType.value = route.query.signType
  matchId = route.query.matchId
  if (signType.value == '2') {
    // 团队-队伍报名-获取队伍
    getTeamList(matchId, groupId.value)
  } else {
    getSignInfoList()
  }
  if (signType.value == '0') {
    geren()
  } else {
    tuandui()
  }
  getMatch(matchId)
  getTableHead()
  getMySignInfo()
})
function geren() {
  match.getChooseDoneSingleCoachs(matchId).then(res => {
    names.value = res.data
  })
}
function tuandui() {
  match.getChooseDoneGroupCoachs(matchId, groupId.value).then(res => {
    names.value = res.data
  })
}

let chargeFlag
function getMatch(id) {
  match.getMatchById({
    id: id
  }).then(res => {
    chargeFlag = res.data.chargeFlag
    noPhotoCanSign.value = res.data.noPhotoCanSign
    coachOrLeaderFlag.value = res.data.coachOrLeaderFlag
    extraform.value = JSON.parse(res.data.participantsInfo)
  })
}
function getMySignInfo() {
  // 获取已报
  match.getMySignInfo({ 
    cptId: matchId,
    groupId: groupId.value
  }).then(res => {
    tableData.value = res.data.signInfo
    signInfoType = res.data.type
  })
}
function getSignInfoList() {
  // console.log(activeTeam.value)
  match.getMySignInfoList({
    cptId: matchId,
    groupId: groupId.value,
    teamId: activeTeam.value || ''
  }).then(res => {
    signInfoTable.value = res.data
    // if(signInfoTable.value.length>0){
    //   let choosedIds = []
    //   for(let p of choosedList.value){
    //     choosedIds.push(p.id)
    //   }
    //   for(var pp of signInfoTable.value){
    //     if(choosedIds.indexOf(pp.personInfo.id)==-1){
    //       // 判断是否已存在
    //       choosedList.value.push(pp.personInfo)
    //     }
    //   }
    // }
  })
}
function getTableHead() {
  match.getCptExtraInfo(matchId).then(res => {
    // console.log(res.data)
    extraTableHead.value = res.data
  })
}
function getTeamList(a, b) {
  match.getMyTeamList(a, b).then(res => {
    teamList.value = res.data
    activeTeam.value = teamList.value[0].id
    getSignInfoList()
  })
}
function teamClick(tab, event) {
  activeTeam.value = tab.props.name
  getSignInfoList()
}
function submitForm() {
  if (signInfoType == '1') {
    ElMessageBox.confirm('已报项，前往我的报项', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      router.push({ name: 'myMatch' })
    })
    return
  }
  if (extraform.value && extraform.value.length > 0) {
    let needBuchong = false
    for (const e of extraform.value) {
      if (e.status == '0') {
        needBuchong = true
      }
    }
    for (const s of signInfoTable.value) {
      if (s.extraPersonInfo == null && needBuchong) {
        ElMessage.error('请完善运动员补充信息')
        return
      }
    }
  }
  if (signInfoType == '2') {
    match.recoverMySign({ cptId: matchId, groupId: groupId.value }).then(res => {
      if (res.msg.indexOf('Exception:') > -1) {
        const msg = res.msg.slice(10)
        ElMessageBox.confirm(msg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          console.log('用户点击确定')
        })
        return
      } else {
        afterRecover()
      }
    })
  } else {
    afterRecover()
  }
}
function afterRecover() {
  if (signInfoTable.value.length == 0) {
    ElMessage.error('请至少选择一个项目')
    return
  }
  // 判断是否收费
  if (chargeFlag == '0') {
    var obj = {
      cptId: matchId,
      groupId: groupId.value
    }
    match.commitSign(obj).then(res => {
      console.log(res.data)
      showResult.value = true
    })
  } else {
    // 生成账单
    router.push({
      name: 'expenseDetails',
      query: {
        matchId: matchId,
        groupId: groupId.value
      }
    })
  }
}

function goPrev() {
  router.go(-1)
}
function chooseSportman() {
  if (signInfoType == '2') {
    match.recoverMySign({
      cptId: matchId,
      groupId: groupId.value
    }).then(res => {
      if (res.msg.indexOf('Exception:') > -1) {
        const msg = res.msg.slice(10)
        ElMessageBox.confirm(msg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          console.log('用户点击确定')
        })
        return
      }
      getMySignInfo()
    })
  }

  const params = {
    title: '选择运动员',
    matchId: matchId,
    groupId: groupId.value,
    rankId: activeTeam.value,
    signType: signType.value,
    noPhotoCanSign: noPhotoCanSign.value,
    coachOrLeaderFlag: coachOrLeaderFlag.value,
    choosedList: choosedList.value
  }
  proxy.$refs['dialogAllSportsmanListRef'].open(params)
}
function getChoosed(list) {
  choosedList.value = list
}

function addCoach() {
  if (signInfoType == '2') {
    match.recoverMySign({
      cptId: matchId,
      groupId: groupId.value
    }).then(res => {
      if (res.msg.indexOf('Exception:') > -1) {
        const msg = res.msg.slice(10)
        ElMessageBox.confirm(msg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          console.log('用户点击确定')
        })
        return
      }
      getMySignInfo()
    })
  }
  const params = {
    title: '新增运动员',
    id: 0,
    groupId: groupId.value
  }
  proxy.$refs['dialogAddCoachRef'].open(params)
}
function signForThisMan(p) {
  activeId.value=p.id
  const params = {
    title: '选择报项',
    matchId: matchId,
    groupId: groupId.value,
    rankId: activeTeam.value,
    signType: signType.value,
    noPhotoCanSign: noPhotoCanSign.value,
    coachOrLeaderFlag: coachOrLeaderFlag.value,
    personal: p,
    choosedList: choosedList.value
  }
  proxy.$refs['dialogSportsmanListRef'].open(params)
}

function delthischoosed(p) {
  choosedList.value = _.without(choosedList.value, p)
}
function delchoosedchoosed() {
  // console.log(choosedchoosed.value)
  // for (var c of choosedList.value) {
  //   if (choosedchoosed.value.indexOf(c.id) > -1) {
  //     choosedList.value = _.without(choosedList.value, c)
  //   }
  // }
  choosedList.value=[]
  choosedchoosed.value = []
  activeId.value=null
}
function editThis(row) {
  activeId.value=row.personId
  const params = {
    title: '选择报项',
    personal: row.cptPersonInfo,
    matchId: matchId,
    groupId: groupId.value,
    rankId: activeTeam.value,
    signType: signType.value,
    noPhotoCanSign: noPhotoCanSign.value,
    coachOrLeaderFlag: coachOrLeaderFlag.value
  }
  proxy.$refs['dialogSportsmanListRef'].open(params)
}
function editMates(row){
  const params = {
    title: '更换队友'
  }
  proxy.$refs['dialogMatesRef'].open(params)
}

function removeThis(id) {
  ElMessageBox.confirm('确定移除这条报项吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    match.deleteSign(id).then(res => {
      // 重新获取已报名信息
      ElMessage.success('已移除该报项')
      getSignInfoList()
      activeId.value=null
  //    let p={}
  //     choosedList.value.forEach(item=>{
  //       if(item.id==activeId.value){
  //         console.log(item)
  //         p=item
  //       }
  //     })
  //     console.log('pppp',p)
  //     const params = {
  //     title: '选择报项',
  //     matchId: matchId,
  //     groupId: groupId.value,
  //     rankId: activeTeam.value,
  //     signType: signType.value,
  //     noPhotoCanSign: noPhotoCanSign.value,
  //     coachOrLeaderFlag: coachOrLeaderFlag.value,
  //     personal: p,
  //     choosedList: choosedList.value
  //   }
  // proxy.$refs['dialogSportsmanListRef'].open(params)


    })
  })
}
function changeCoach(cptId, groupId) {
  // 更换教练
  const params = {
    title: '修改教练',
    groupId: groupId,
    cptId: cptId
  }
  proxy.$refs['popChangeCoach'].open(params)
}
function importSportman() {
  const params = {
    title: '批量导入人员',
    groupId: groupId.value
  }
  proxy.$refs['dialogImportProps'].open(params)
}
function goMySign() {
  router.push({
    name: 'myMatch'
  })
}

const goPersonInfo = (row) => {
  if (signInfoType == '1') {
    ElMessageBox.alert('已报项，前往我的报项', '提示', {
      confirmButtonText: 'OK',
      callback: (Action) => {
        router.push({ name: 'myMatch' })
      }
    })
    return
  }
  // 完善补充信息
  console.log(row)

  const params = {
    title: '完善补充信息',
    participantsInfoArr: extraform.value,
    personId: row.personInfo.id,
    extraId: row.extraPersonInfo?.id || 0
  }
  proxy.$refs['popExtraForm'].open(_.cloneDeep(params))
}
function downloadVoucher() {
  // 下载凭证
  proxy.download(
    `/pdf/getPayedOrderPdf/${matchId}/${groupId.value || 0}`, {}, '报项凭证.pdf'
  )
}
</script>

<style scoped lang="scss">
@import '@/assets/styles/variables.module.scss';
	.app-container{ padding: 0;background: #F5F7F9;}
	.panel-footer .el-button--success{background: linear-gradient(270deg,$--color-primary,$--color-danger);border: none;
		padding: 0 40px;
		font-size: 16px;
	}
	.panel-footer .el-button--success.is-plain{background: #fff;border:1px solid $--color-primary;color: $--color-primary;}
	.hasChoose{margin: 0 0 20px;display: flex;justify-content: space-between; flex-wrap: wrap;
    button{    position: relative;margin: 10px;}
    .choseItem{margin: 10px;position: relative;
      display:flex;
      justify-content: space-between;
      align-items: center;
      width:150px;
      border:1px solid $--color-danger;
      border-radius:4px;
      color:$--color-danger;
      padding:8px 15px;
      
      p{
        margin:0;
        cursor: pointer;
        
      }
      .poClose{position: absolute; right: -6px;top: -12px;z-index: 1;}
    }
    .chooseItemActive{
      background:$--color-danger;
      color:#fff;
    }
  }
  .chooseForm{
		:deep(.el-form-item__content){background: rgba(245, 247, 249, 0.38);padding: 20px 40px 10px;}
		.el-checkbox{height: auto;}
		:deep(.el-checkbox__input){position: absolute;right: 0;top: 0;}
		.name{text-align: center;}
	}
  .namesUl{    display: flex;
    flex-wrap: wrap;
    //justify-content: space-between;
    li{margin-bottom: 6px;
      background:$--color-primary;
      color:#fff;
      padding:10px 20px;
      border-radius:4px;
      margin-left:10px;
    }
    label{margin-right: 4px;}
    span{margin-right: 10px;color: #fff;
      &:after{content: '、';}
      &:last-child:after{display: none;}
    }
  }
  .chooseBottom{
    background:#fff;
    margin-top:20px;
    padding:5px 20px;
  }
</style>
